#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SQL语义分析器
基于语法分析的结果进行语义分析，生成四元式中间代码

实现功能：
1. 语法制导的翻译
2. 四元式中间代码生成
3. 符号表管理
4. 语义错误检查
"""

from typing import Dict, List, Set, Tuple, Optional, Union, Any
from enum import Enum
import copy
import re
from LexicalAnalysis import LexicalAnalyzer, Token, TokenType
from SyntaxAnalysis import SyntaxAnalyzer, Production
from ErrorCorrection import SmartErrorCorrector, ErrorInfo, ErrorType, ErrorSeverity
import os
import sys
# 确保项目根目录在sys.path中，以便导入 OperatingSystem 包
_this_dir = os.path.dirname(os.path.abspath(__file__))
_project_root = os.path.abspath(os.path.join(_this_dir, os.pardir))
if _project_root not in sys.path:
    sys.path.insert(0, _project_root)
# 使用真实磁盘上的数据库元数据
from OperatingSystem.database_manager import DatabaseManager


class QuadrupleOp(Enum):
    """四元式操作符枚举"""
    SELECT = "SELECT"     # 选择操作
    FROM = "FROM"         # 表引用操作
    WHERE = "WHERE"       # 条件过滤操作
    CREATE = "CREATE"     # 创建表操作
    INSERT = "INSERT"     # 插入操作
    DELETE = "DELETE"     # 删除操作
    UPDATE = "UPDATE"     # 更新操作
    DROP = "DROP"         # 删除表操作
    USE = "USE"           # 使用数据库操作
    CREATE_DATABASE = "CREATE_DATABASE"  # 创建数据库操作
    DROP_DATABASE = "DROP_DATABASE"      # 删除数据库操作
    LIST_DATABASES = "LIST_DATABASES"    # 列出数据库操作
    CREATE_USER = "CREATE_USER"          # 创建用户操作
    DROP_USER = "DROP_USER"              # 删除用户操作
    LIST_USERS = "LIST_USERS"            # 列出用户操作
    COLUMN = "COLUMN"     # 列定义操作
    ASSIGN = "="          # 赋值操作
    GT = ">"              # 大于比较
    LT = "<"              # 小于比较
    EQ = "="              # 等于比较
    GE = ">="             # 大于等于比较
    LE = "<="             # 小于等于比较
    NE = "!="             # 不等于比较
    JOIN = "JOIN"         # 连接操作
    ORDER = "ORDER"       # 排序操作
    GROUP = "GROUP"       # 分组操作
    SET = "SET"           # SET操作
    RESULT = "RESULT"     # 结果操作
    TEMP = "TEMP"         # 临时变量生成
    AND = "AND"           # 逻辑与操作
    OR = "OR"             # 逻辑或操作
    LIKE = "LIKE"         # 模式匹配操作
    LIMIT = "LIMIT"       # 限制结果数量操作
    UNION = "UNION"       # 并集操作
    AGGREGATE = "AGGREGATE" # 聚合函数操作
    GRANT = "GRANT"       # 权限授予操作
    HAVING = "HAVING"     # HAVING子句操作


class Quadruple:
    """四元式类 [op, arg1, arg2, result]"""
    
    def __init__(self, op: str, arg1: str = "-", arg2: str = "-", result: str = "-"):
        self.op = op          # 操作符
        self.arg1 = arg1      # 第一个操作数
        self.arg2 = arg2      # 第二个操作数
        self.result = result  # 结果
    
    def __str__(self):
        return f"({self.op}, {self.arg1}, {self.arg2}, {self.result})"
    
    def __repr__(self):
        return self.__str__()


class SymbolTableEntry:
    """符号表条目"""
    
    def __init__(self, name: str, symbol_type: str, value: Any = None, line: int = 0, column: int = 0):
        self.name = name              # 符号名称
        self.type = symbol_type       # 符号类型 (table, column, temp)
        self.value = value            # 符号值
        self.line = line              # 定义行号
        self.column = column          # 定义列号
        self.used = False             # 是否被使用
    
    def __str__(self):
        return f"{self.name}({self.type})"


class SemanticAnalyzer:
    """语义分析器"""
    
    def __init__(self, use_test_data=True, enable_optimization=True):
        # 四元式序列
        self.quadruples: List[Quadruple] = []
        
        # 符号表栈，支持作用域
        self.symbol_table_stack: List[Dict[str, SymbolTableEntry]] = []
        self.symbol_table: Dict[str, SymbolTableEntry] = {}
        self.symbol_table_stack.append(self.symbol_table)  # 全局作用域
        
        # 临时变量计数器
        self.temp_counter = 0
        
        # 当前分析的token序列
        self.tokens: List[Token] = []
        self.current_token_index = 0
        
        # 语义栈，用于存储中间结果
        self.semantic_stack: List[Dict[str, Any]] = []
        
        # 错误列表
        self.errors: List[str] = []
        
        # 智能纠错器
        self.error_corrector = SmartErrorCorrector()
        
        # 当前使用的数据库
        self.current_database = None
        
        # 测试模式开关
        self.use_test_data = use_test_data
        
        # 查询优化开关
        self.enable_optimization = enable_optimization
        self.query_optimizer = None
        self.optimization_stats = None

        # 预定义的数据库信息
        self.predefined_databases = {
            "test_db", "hr_system", "finance_system", "project_system", 
            "school_db", "company_db", "inventory_db","company_db1","system"
        }
        
        # 预定义的用户信息
        self.predefined_users = {
            "root", "admin", "user1", "user2", "guest", 
            "alice", "bob", "charlie", "manager", "developer",
            "old_user", "test_user", "new_user", "test_user1"
        }

        # 预定义的表和列信息（用于语义检查）
        self.predefined_tables = {
            "Students": ["name", "age", "id", "major"],
            "Teachers": ["name", "age", "id", "department"],
            "Courses": ["name", "credits", "id", "teacher_id"],
            "student": ["id", "name", "age", "major"],
            "users": ["id", "name", "age"],  # demo中用到的用户表
            "orders": ["order_id", "user_id", "amount", "status"],  # demo中用到的订单表
            "test_users": ["id", "name", "age"],  # 调试测试用的表
            "employees": ["emp_id", "emp_name", "dept_id"],  # 员工表，用于连接测试
            "departments": ["dept_id", "dept_name", "location"],  # 部门表，用于连接测试
        }

        # 存储适配器（用于动态获取表信息）
        self.storage_adapter = None
        
        # 根据模式选择数据源
        if self.use_test_data:
            # 测试模式：使用预定义数据
            self.db_manager = None
            print("[SemanticAnalyzer] 使用测试模式 - 预定义数据")
        else:
            # 真实模式：使用磁盘数据库
            project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
            self.real_data_root = os.path.join(project_root, "database")
            self.db_manager = DatabaseManager(data_root=self.real_data_root)
            print("[SemanticAnalyzer] 使用真实模式 - 磁盘数据库")

        # 表别名映射：别名 -> 实际表名
        self.table_aliases = {}
    
    def generate_temp(self) -> str:
        """生成临时变量名"""
        self.temp_counter += 1
        temp_name = f"T{self.temp_counter}"
        # 将临时变量加入符号表
        self.symbol_table[temp_name] = SymbolTableEntry(temp_name, "temp")
        return temp_name
    
    def emit(self, op: str, arg1: str = "-", arg2: str = "-", result: str = "-") -> int:
        """生成四元式"""
        quad = Quadruple(op, arg1, arg2, result)
        self.quadruples.append(quad)
        return len(self.quadruples) - 1  # 返回四元式的地址
    
    def enter_scope(self):
        """进入新的作用域"""
        new_scope = {}
        self.symbol_table_stack.append(new_scope)
        self.symbol_table = new_scope
    
    def exit_scope(self):
        """退出当前作用域"""
        if len(self.symbol_table_stack) > 1:
            self.symbol_table_stack.pop()
            self.symbol_table = self.symbol_table_stack[-1]
    
    def add_symbol(self, name: str, symbol_type: str, line: int = 0, column: int = 0) -> bool:
        """添加符号到当前作用域的符号表"""
        if name in self.symbol_table:
            self.errors.append(f"符号 '{name}' 在第{line}行第{column}列重复定义")
            return False
        
        self.symbol_table[name] = SymbolTableEntry(name, symbol_type, None, line, column)
        return True
    
    def lookup_symbol(self, name: str) -> Optional[SymbolTableEntry]:
        """查找符号（从当前作用域向上查找）"""
        # 从当前作用域开始，向上查找
        for scope in reversed(self.symbol_table_stack):
            if name in scope:
                return scope[name]
        return None
    
    def check_database_exists(self, database_name: str) -> bool:
        """检查数据库是否存在"""
        # 首先从预定义数据库中查找
        if database_name in self.predefined_databases:
            return True
        
        # 如果有存储适配器，从存储引擎实时查找
        if hasattr(self, 'storage_adapter') and self.storage_adapter:
            try:
                database_list = self.storage_adapter.get_accessible_databases()
                if database_name in database_list:
                    return True
            except Exception as e:
                print(f"[SemanticAnalyzer] 从存储引擎检查数据库失败: {e}")
        
        # 如果不是测试模式，尝试从磁盘数据库检查
        if not self.use_test_data and self.db_manager:
            try:
                return self.db_manager.database_exists(database_name)
            except Exception as e:
                print(f"[SemanticAnalyzer] 检查数据库存在性异常: {e}")
        
        return False
    
    def check_user_exists(self, username: str) -> bool:
        """检查用户是否存在"""
        # 首先从预定义用户中查找
        if username in self.predefined_users:
            return True
        
        # 如果有存储适配器，从存储引擎实时查找
        if hasattr(self, 'storage_adapter') and self.storage_adapter:
            try:
                # 注意：这里需要根据你的存储适配器API调整
                # 如果存储适配器有用户管理功能，可以在这里调用
                # 目前暂时返回False，表示可以创建新用户
                pass
            except Exception as e:
                print(f"[SemanticAnalyzer] 从存储引擎检查用户失败: {e}")
        
        return False
    
    def check_table_exists(self, table_name: str) -> bool:
        """检查表是否存在"""
        # 首先从预定义表中查找
        if table_name in self.predefined_tables:
            return True
        
        # 如果有存储适配器，从存储引擎实时查找
        if hasattr(self, 'storage_adapter') and self.storage_adapter:
            try:
                table_list = self.storage_adapter.get_current_database_tables()
                if table_name in table_list:
                    # 动态加载表结构到预定义表中
                    self._load_table_schema_from_storage(table_name)
                    return True
            except Exception as e:
                print(f"[SemanticAnalyzer] 从存储引擎检查表失败: {e}")
        
        # 如果不是测试模式，尝试从磁盘数据库检查
        if not self.use_test_data and self.db_manager:
            try:
                # 先在当前数据库中检查
                if self.current_database and self.check_database_exists(self.current_database):
                    db = self.db_manager.get_database(self.current_database)
                    if db and table_name in db.list_tables():
                        # 动态加载表结构
                        self._load_table_schema_from_db(table_name, db)
                        return True
                # 扫描所有数据库
                for db_name in self.db_manager.list_databases():
                    db = self.db_manager.get_database(db_name)
                    if db and table_name in db.list_tables():
                        # 动态加载表结构
                        self._load_table_schema_from_db(table_name, db)
                        return True
            except Exception as e:
                print(f"[SemanticAnalyzer] 检查表存在性异常: {e}")
        
        return False
    
    def _load_table_schema(self, table_name: str) -> Optional[List[str]]:
        """加载表结构，返回列名列表"""
        if self.use_test_data:
            # 测试模式：使用预定义表结构
            return self.predefined_tables.get(table_name)
        else:
            # 真实模式：从磁盘加载表结构
            try:
                # 优先当前数据库
                if self.current_database and self.check_database_exists(self.current_database):
                    db = self.db_manager.get_database(self.current_database)
                    if db:
                        schema = db.get_table_schema(table_name)
                        if schema:
                            return [col.name for col in schema.columns]
                # 扫描所有数据库
                for db_name in self.db_manager.list_databases():
                    db = self.db_manager.get_database(db_name)
                    if db:
                        schema = db.get_table_schema(table_name)
                        if schema:
                            return [col.name for col in schema.columns]
            except Exception as e:
                print(f"[SemanticAnalyzer] 加载表结构失败 {table_name}: {e}")
            return None
    
    def _load_table_schema_from_storage(self, table_name: str):
        """从存储引擎动态加载表结构"""
        try:
            if hasattr(self, 'storage_adapter') and self.storage_adapter:
                # 获取表的列信息（需要根据你的存储适配器API调整）
                # 这里假设存储适配器有获取表结构的方法
                if hasattr(self.storage_adapter, 'os_storage') and self.storage_adapter.os_storage:
                    schema = self.storage_adapter.os_storage.table_schemas.get(table_name)
                    if schema:
                        column_names = [col.name for col in schema.columns]
                        self.predefined_tables[table_name] = column_names
                        print(f"[SemanticAnalyzer] 动态加载表结构: {table_name} -> {column_names}")
        except Exception as e:
            print(f"[SemanticAnalyzer] 从存储引擎加载表结构失败 {table_name}: {e}")
    
    def _load_table_schema_from_db(self, table_name: str, db):
        """从数据库管理器动态加载表结构"""
        try:
            schema = db.get_table_schema(table_name)
            if schema:
                column_names = [col.name for col in schema.columns]
                self.predefined_tables[table_name] = column_names
                print(f"[SemanticAnalyzer] 从数据库动态加载表结构: {table_name} -> {column_names}")
        except Exception as e:
            print(f"[SemanticAnalyzer] 从数据库加载表结构失败 {table_name}: {e}")
    
    def set_storage_adapter(self, storage_adapter):
        """设置存储适配器，用于动态获取表信息"""
        self.storage_adapter = storage_adapter
        print(f"[SemanticAnalyzer] 已设置存储适配器，启用动态数据源支持")
    
    def check_column_exists(self, table_name: str, column_name: str) -> bool:
        """检查列是否存在于指定表中"""
        # 首先检查预定义表结构
        if table_name in self.predefined_tables:
            return column_name in self.predefined_tables[table_name]
        
        # 如果表不在预定义中，尝试动态加载
        if self.check_table_exists(table_name):
            # 表存在，再次检查列（因为check_table_exists可能已经加载了表结构）
            if table_name in self.predefined_tables:
                return column_name in self.predefined_tables[table_name]
        
        return False
    
    def resolve_table_name(self, table_or_alias: str) -> str:
        """解析表名或别名，返回实际表名"""
        if table_or_alias in self.table_aliases:
            return self.table_aliases[table_or_alias]
        return table_or_alias
    
    def semantic_error(self, message: str, line: int = 0, column: int = 0):
        """记录语义错误"""
        error_msg = f"语义错误"
        if line > 0 and column > 0:
            error_msg += f" (第{line}行第{column}列)"
        error_msg += f": {message}"
        self.errors.append(error_msg)
        print(error_msg)
        
        # 同时记录到智能纠错器
        self._record_semantic_error(message, line, column)
    
    def analyze(self, tokens: List[Token]) -> Tuple[List[Quadruple], Dict[str, SymbolTableEntry], List[str]]:
        """
        语义分析主函数
        返回: (四元式列表, 符号表, 错误列表)
        """
        print("\n=== 开始语义分析 ===")
        
        self.tokens = tokens
        self.current_token_index = 0
        self.quadruples = []
        self.symbol_table = {}
        self.semantic_stack = []
        self.errors = []
        self.temp_counter = 0
        self.table_aliases = {}  # 重置表别名映射
        
        # 清空纠错器的错误记录
        self.error_corrector.clear_errors()
        
        # 开始语义分析
        try:
            self._analyze_program()
        except Exception as e:
            self.semantic_error(f"语义分析过程中发生异常: {str(e)}")
        
        # 应用查询优化（如果启用）
        if self.enable_optimization and not self.errors:
            try:
                from query_optimizer import QueryOptimizer
                self.query_optimizer = QueryOptimizer()
                optimized_quadruples, self.optimization_stats = self.query_optimizer.optimize(
                    self.quadruples, self.symbol_table
                )
                # 更新四元式为优化后的版本
                self.quadruples = optimized_quadruples
            except ImportError:
                print("警告: 无法导入查询优化器模块，跳过优化")
            except Exception as e:
                print(f"警告: 查询优化过程中发生错误: {e}")
        
        # 进行智能纠错分析
        self._perform_error_correction()
        
        # 打印结果
        self._print_results()
        
        return self.quadruples, self.symbol_table, self.errors
    
    def _analyze_program(self):
        """分析程序 - 对应 Prog -> Stmt ;"""
        print("分析程序结构...")
        
        # 分析SQL语句
        self._analyze_statement()
        
        # 检查分号
        if self._current_token() and self._current_token().value == ';':
            self._advance()
        
        # 生成结果四元式
        if self.quadruples:
            # 获取最后一个临时变量作为最终结果
            last_temp = f"T{self.temp_counter}" if self.temp_counter > 0 else "-"
            self.emit("RESULT", last_temp, "-", "-")
    
    def _analyze_statement(self):
        """分析SQL语句 - 对应 Stmt -> SelectStmt | CreateStmt | InsertStmt | DeleteStmt | UpdateStmt"""
        print("分析SQL语句...")
        
        current = self._current_token()
        if not current:
            self.semantic_error("输入为空")
            return
        
        keyword = current.value.upper()
        if keyword == "SELECT":
            self._analyze_select_statement()
        elif keyword == "CREATE":
            self._analyze_create_statement()
        elif keyword == "INSERT":
            self._analyze_insert_statement()
        elif keyword == "DELETE":
            self._analyze_delete_statement()
        elif keyword == "UPDATE":
            self._analyze_update_statement()
        elif keyword == "DROP":
            self._analyze_drop_statement()
        elif keyword == "USE":
            self._analyze_use_statement()
        elif keyword == "GRANT":
            self._analyze_grant_statement()
        elif keyword == "LIST" or keyword == "SHOW":
            self._analyze_list_statement()
        else:
            self.semantic_error(f"未知的SQL语句类型: {keyword}", current.line, current.column)
    
    def _analyze_select_statement(self):
        """分析SELECT语句 - 对应 SelectStmt -> SimpleSelect UnionClause"""
        print("分析SELECT语句...")
        
        # 分析第一个简单SELECT语句
        first_select_result = self._analyze_simple_select()
        if not first_select_result:
            return None
        
        current_temp = first_select_result
        
        # 分析UNION子句（如果有）
        while self._current_token() and self._current_token().value.upper() == "UNION":
            self._advance()  # 跳过UNION关键字
            
            # 检查是否有ALL关键字
            is_union_all = False
            if self._current_token() and self._current_token().value.upper() == "ALL":
                is_union_all = True
                self._advance()  # 跳过ALL关键字
            
            # 分析第二个简单SELECT语句
            second_select_result = self._analyze_simple_select()
            if not second_select_result:
                break
            
            # 生成UNION四元式
            union_temp = self.generate_temp()
            union_type = "UNION_ALL" if is_union_all else "UNION"
            self.emit("UNION", f"{union_type}:{current_temp}:{second_select_result}", "-", union_temp)
            
            current_temp = union_temp
        
        return current_temp
    
    def _analyze_simple_select(self) -> Optional[str]:
        """分析简单SELECT语句"""
        print("分析简单SELECT语句...")
        
        # 检查SELECT关键字
        if not self._expect_keyword("SELECT"):
            return None
        
        # 分析选择列表
        select_attrs = self._analyze_select_list()
        
        # 分析FROM子句
        table_info = self._analyze_from_clause()
        
        # 分析WHERE子句（可选）
        where_condition = self._analyze_where_clause()
        
        # 分析GROUP BY子句（可选）
        group_info = self._analyze_group_clause()
        
        # 分析HAVING子句（可选）
        having_condition = self._analyze_having_clause()
        
        # 分析ORDER BY子句（可选）- 注意：在UNION中，ORDER BY通常只能在最后使用
        order_info = None
        if (self._current_token() and 
            self._current_token().value.upper() == "ORDER" and
            not self._has_union_after_current_position()):
            order_info = self._analyze_order_clause()
        
        # 分析LIMIT子句（可选）
        limit_info = None
        if (self._current_token() and 
            self._current_token().value.upper() == "LIMIT" and
            not self._has_union_after_current_position()):
            limit_info = self._analyze_limit_clause()
        
        # 语义检查：验证表是否存在
        if table_info and table_info.get('main_table'):
            main_table = table_info['main_table']
            if not self.check_table_exists(main_table):
                current_token = self._current_token()
                if current_token:
                    self.semantic_error(f"表 '{main_table}' 不存在", current_token.line, current_token.column)
        
        # 语义检查：验证列是否存在于表中（排除聚合函数）
        if table_info and select_attrs:
            main_table = table_info.get('main_table')
            alias = table_info.get('alias')
            if main_table:
                for attr in select_attrs:
                    if attr != "*":
                        # 检查是否是聚合函数（包含括号的表达式）
                        if self._is_aggregate_function(attr):
                            # 聚合函数不需要进行列名验证，跳过
                            continue
                        
                        # 检查是否是qualified identifier (table.column)
                        if '.' in attr:
                            table_part, column_part = attr.split('.', 1)
                            # 解析表名或别名
                            actual_table = self.resolve_table_name(table_part)
                            if self.check_table_exists(actual_table):
                                if not self.check_column_exists(actual_table, column_part):
                                    current_token = self._current_token()
                                    if current_token:
                                        self.semantic_error(f"列 '{column_part}' 不存在于表 '{actual_table}' 中", 
                                                          current_token.line, current_token.column)
                            else:
                                current_token = self._current_token()
                                if current_token:
                                    self.semantic_error(f"表或别名 '{table_part}' 未定义", 
                                                      current_token.line, current_token.column)
                        else:
                            # 普通列名
                            if not self.check_column_exists(main_table, attr):
                                current_token = self._current_token()
                                if current_token:
                                    self.semantic_error(f"列 '{attr}' 不存在于表 '{main_table}' 中", 
                                                      current_token.line, current_token.column)
        
        # 生成四元式
        if table_info:
            current_temp = table_info.get('result_temp')
            
            # 生成WHERE四元式（如果有条件）
            if where_condition:
                where_temp = self.generate_temp()
                self.emit("WHERE", where_condition, current_temp, where_temp)
                current_temp = where_temp  # 更新表引用
            
            # 生成GROUP BY四元式（如果有分组）
            if group_info:
                group_temp = self.generate_temp()
                group_columns = ','.join(group_info)
                self.emit("GROUP", group_columns, current_temp, group_temp)
                current_temp = group_temp
            
            # 生成HAVING四元式（如果有HAVING条件）
            if having_condition:
                having_temp = self.generate_temp()
                self.emit("HAVING", having_condition, current_temp, having_temp)
                current_temp = having_temp
            
            # 生成ORDER BY四元式（如果有排序）
            if order_info:
                order_temp = self.generate_temp()
                order_spec = ','.join([f"{col}:{direction}" for col, direction in order_info])
                self.emit("ORDER", order_spec, current_temp, order_temp)
                current_temp = order_temp
            
            # 生成LIMIT四元式（如果有限制）
            if limit_info:
                limit_temp = self.generate_temp()
                self.emit("LIMIT", str(limit_info), current_temp, limit_temp)
                current_temp = limit_temp
            
            # 生成SELECT四元式
            if select_attrs:
                for attr in select_attrs:
                    attr_temp = self.generate_temp()
                    self.emit("SELECT", attr, current_temp, attr_temp)
                    current_temp = attr_temp  # 更新当前结果
            
            return current_temp
        
        return None
    
    def _analyze_select_list(self) -> List[str]:
        """分析选择列表 - 对应 SelList -> SelectItem SelRest | *"""
        print("分析选择列表...")
        
        select_attrs = []
        
        current_token = self._current_token()
        if not current_token:
            return select_attrs
        
        # 检查是否是*符号
        if current_token.type == TokenType.OPERATOR and current_token.value == '*':
            select_attrs.append('*')
            self._advance()
        # 分析select item（可能是qualified identifier或聚合函数）
        else:
            select_item = self._analyze_select_item()
            if select_item:
                select_attrs.append(select_item)
            
            # 分析剩余的选择列表
            more_attrs = self._analyze_select_rest()
            select_attrs.extend(more_attrs)
        
        return select_attrs
    
    def _analyze_select_rest(self) -> List[str]:
        """分析选择列表剩余部分 - 对应 SelRest -> , SelList | ε"""
        print("分析选择列表剩余部分...")
        
        select_attrs = []
        
        # 如果当前是逗号，继续分析
        if self._current_token() and self._current_token().value == ',':
            self._advance()  # 跳过逗号
            
            # 递归分析选择列表
            more_attrs = self._analyze_select_list()
            select_attrs.extend(more_attrs)
        
        # 否则是空产生式，不做任何操作
        return select_attrs
    
    def _analyze_select_item(self) -> Optional[str]:
        """分析选择项 - 对应 SelectItem -> QualifiedID | AggregateFunc"""
        print("分析选择项...")
        
        current_token = self._current_token()
        if not current_token:
            return None
        
        # 检查是否是聚合函数
        if (current_token.type == TokenType.KEYWORD and 
            current_token.value.upper() in {'COUNT', 'SUM', 'AVG', 'MAX', 'MIN', 'STDDEV', 'VARIANCE'}):
            return self._analyze_aggregate_function()
        # 否则是qualified identifier
        elif current_token.type == TokenType.IDENTIFIER:
            return self._analyze_qualified_identifier()
        
        return None
    
    def _analyze_aggregate_function(self) -> Optional[str]:
        """分析聚合函数 - 对应 AggregateFunc -> AggregateType ( QualifiedID ) | AggregateType ( * )"""
        print("分析聚合函数...")
        
        current_token = self._current_token()
        if not current_token or current_token.type != TokenType.KEYWORD:
            return None
        
        # 获取聚合函数类型
        func_type = current_token.value.upper()
        if func_type not in {'COUNT', 'SUM', 'AVG', 'MAX', 'MIN', 'STDDEV', 'VARIANCE'}:
            self.semantic_error(f"未知的聚合函数: {func_type}", current_token.line, current_token.column)
            return None
        
        self._advance()  # 跳过函数名
        
        # 检查左括号
        if not self._current_token() or self._current_token().value != '(':
            self.semantic_error("聚合函数后面必须跟 '('")
            return None
        self._advance()  # 跳过左括号
        
        # 分析参数（可能是*或qualified identifier）
        param = None
        current_token = self._current_token()
        if current_token and current_token.type == TokenType.OPERATOR and current_token.value == '*':
            # COUNT(*) 情况
            if func_type != 'COUNT':
                self.semantic_error(f"聚合函数 {func_type} 不支持 * 参数", current_token.line, current_token.column)
                return None
            param = '*'
            self._advance()
        elif current_token and current_token.type == TokenType.IDENTIFIER:
            # 普通列名参数
            param = self._analyze_qualified_identifier()
            if not param:
                return None
        else:
            self.semantic_error("聚合函数参数必须是列名或 *")
            return None
        
        # 检查右括号
        if not self._current_token() or self._current_token().value != ')':
            self.semantic_error("聚合函数缺少 ')'")
            return None
        self._advance()  # 跳过右括号
        
        # 生成聚合函数四元式
        result_temp = self.generate_temp()
        aggregate_spec = f"{func_type}:{param}"
        self.emit("AGGREGATE", aggregate_spec, "-", result_temp)
        
        # 返回聚合函数的表示形式
        return f"{func_type}({param})"
    
    def _analyze_qualified_identifier(self) -> Optional[str]:
        """分析限定标识符 - 对应 QualifiedID -> ID QualifiedIDRest"""
        if not self._current_token() or self._current_token().type != TokenType.IDENTIFIER:
            return None
        
        # 读取第一个标识符
        first_id = self._current_token().value
        self._advance()
        
        # 检查是否有点号
        if self._current_token() and self._current_token().value == '.':
            self._advance()  # 跳过点号
            
            # 读取第二个标识符
            if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
                second_id = self._current_token().value
                self._advance()
                return f"{first_id}.{second_id}"
            else:
                self.semantic_error("期望标识符")
                return first_id
        else:
            # 没有点号，只是普通标识符
            return first_id
    
    def _analyze_table(self) -> Optional[str]:
        """分析表名 - 对应 Tbl -> ID"""
        print("分析表名...")
        
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            table_name = self._current_token().value
            
            # 将表名加入符号表
            current_token = self._current_token()
            self.add_symbol(table_name, "table", current_token.line, current_token.column)
            
            self._advance()
            return table_name
        
        return None
    
    def _analyze_table_alias(self) -> Optional[Dict[str, Any]]:
        """分析表别名 - 对应 TblAlias -> ID TblAliasRest"""
        if not self._current_token() or self._current_token().type != TokenType.IDENTIFIER:
            return None
        
        # 读取表名
        table_name = self._current_token().value
        self._advance()
        
        # 检查是否有别名
        alias = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            # 检查下一个token是否是关键字（如JOIN, WHERE等），如果是则不是别名
            next_token_value = self._current_token().value.upper()
            if next_token_value not in ['JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL', 'WHERE', 'ORDER', 'GROUP', 'LIMIT']:
                alias = self._current_token().value
                self._advance()
        
        # 将表名和别名加入符号表
        current_token = self._current_token()
        if current_token:
            self.add_symbol(table_name, "table", current_token.line, current_token.column)
            if alias:
                self.add_symbol(alias, "alias", current_token.line, current_token.column)
                # 维护别名映射
                self.table_aliases[alias] = table_name
        
        return {
            'table_name': table_name,
            'alias': alias
        }
    
    def _current_token(self) -> Optional[Token]:
        """获取当前token"""
        if self.current_token_index < len(self.tokens):
            return self.tokens[self.current_token_index]
        return None
    
    def _advance(self):
        """移动到下一个token"""
        self.current_token_index += 1
    
    def _expect_keyword(self, keyword: str) -> bool:
        """期望特定关键字"""
        current = self._current_token()
        if current and current.type == TokenType.KEYWORD and current.value.upper() == keyword.upper():
            self._advance()
            return True
        
        if current:
            self.semantic_error(f"期望关键字 '{keyword}'，但得到 '{current.value}'", 
                              current.line, current.column)
        else:
            self.semantic_error(f"期望关键字 '{keyword}'，但输入已结束")
        
        return False
    
    def _analyze_create_statement(self):
        """分析CREATE语句（TABLE或DATABASE）"""
        print("分析CREATE语句...")
        
        # 检查CREATE关键字
        if not self._expect_keyword("CREATE"):
            return
        
        # 检查下一个关键字是TABLE还是DATABASE
        current = self._current_token()
        if not current or current.type != TokenType.KEYWORD:
            self.semantic_error("CREATE后面必须跟TABLE或DATABASE关键字")
            return
        
        next_keyword = current.value.upper()
        if next_keyword == "TABLE":
            self._analyze_create_table_statement()
        elif next_keyword == "DATABASE":
            self._analyze_create_database_statement()
        elif next_keyword == "USER":
            self._analyze_create_user_statement()
        else:
            self.semantic_error(f"CREATE后面不支持的关键字: {next_keyword}")
    
    def _analyze_create_table_statement(self):
        """分析CREATE TABLE语句"""
        print("分析CREATE TABLE语句...")
        
        # 检查TABLE关键字
        if not self._expect_keyword("TABLE"):
            return
        
        # 分析表名
        table_name = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            table_name = self._current_token().value
            current_token = self._current_token()
            self.add_symbol(table_name, "table", current_token.line, current_token.column)
            self._advance()
        else:
            self.semantic_error("期望表名")
            return
        
        # 检查左括号
        if not self._current_token() or self._current_token().value != '(':
            self.semantic_error("期望 '('")
            return
        self._advance()
        
        # 分析列定义列表
        columns = self._analyze_column_definitions()
        print(f"[DEBUG] columns类型: {type(columns)}, 值: {columns}")
        
        # 检查右括号
        if not self._current_token() or self._current_token().value != ')':
            self.semantic_error("期望 ')'")
            return
        self._advance()
        
        # 生成四元式
        if table_name:
            table_temp = self.generate_temp()
            self.emit("CREATE", table_name, "-", table_temp)
            
            # 为每个列生成COLUMN四元式
            for col_name, col_type in columns:
                self.emit("COLUMN", col_name, col_type, table_temp)
    
    def _analyze_insert_statement(self):
        """分析INSERT语句"""
        print("分析INSERT语句...")
        
        # 检查INSERT关键字
        if not self._expect_keyword("INSERT"):
            return
        
        # 检查INTO关键字
        if not self._expect_keyword("INTO"):
            return
        
        # 分析表名
        table_name = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            table_name = self._current_token().value
            self._advance()
        else:
            self.semantic_error("期望表名")
            return
        
        # 检查表是否存在
        if table_name and not self.check_table_exists(table_name):
            current_token = self._current_token()
            if current_token:
                self.semantic_error(f"表 '{table_name}' 不存在", current_token.line, current_token.column)
        
        # 检查是否有列名列表（两种INSERT形式）
        columns = None
        has_column_list = False
        
        # 检查当前token是否为左括号（表示有列名列表）或VALUES（表示无列名列表）
        if self._current_token() and self._current_token().value == '(':
            # 形式1: INSERT INTO table (col1, col2, ...) VALUES (val1, val2, ...)
            has_column_list = True
            self._advance()  # 跳过左括号
            
            # 分析列名列表
            columns = self._analyze_select_list()
            
            # 检查右括号
            if not self._current_token() or self._current_token().value != ')':
                self.semantic_error("期望 ')'")
                return
            self._advance()
            
        elif self._current_token() and self._current_token().value.upper() == 'VALUES':
            # 形式2: INSERT INTO table VALUES (val1, val2, ...)
            has_column_list = False
            # 不需要分析列名列表，将使用表的所有列按顺序
        else:
            self.semantic_error("期望 '(' 或 'VALUES'")
            return
        
        # 检查VALUES关键字
        if not self._expect_keyword("VALUES"):
            return
        
        # 检查左括号
        if not self._current_token() or self._current_token().value != '(':
            self.semantic_error("期望 '('")
            return
        self._advance()
        
        # 分析值列表
        values = self._analyze_value_list()
        
        # 检查右括号
        if not self._current_token() or self._current_token().value != ')':
            self.semantic_error("期望 ')'")
            return
        self._advance()
        
        # 语义检查：列数和值数是否匹配
        if has_column_list and columns and len(columns) != len(values):
            self.semantic_error(f"列数({len(columns)})与值数({len(values)})不匹配")
            return
        elif not has_column_list:
            # 对于没有列名列表的INSERT，检查值的数量是否与表的列数匹配
            # 这里简化处理，假设表存在且可以获取列信息
            pass  # 在实际实现中应该检查表的列数
        
        # 生成四元式
        table_temp = self.generate_temp()
        
        # INSERT四元式
        self.emit("INSERT", table_name, "-", table_temp)
        
        # 如果有列名列表，为每个列-值对生成赋值四元式
        if has_column_list and columns:
            for i, (column, value) in enumerate(zip(columns, values)):
                value_temp = f"{table_temp}.{column}"
                self.emit("=", value, "-", value_temp)
        else:
            # 没有列名列表，按顺序为每个值生成四元式
            for i, value in enumerate(values):
                value_temp = f"{table_temp}.{i}"
                self.emit("=", value, "-", value_temp)
        
        # 结果四元式
        result_temp = self.generate_temp()
        self.emit("RESULT", table_temp, "-", result_temp)
    
    def _analyze_delete_statement(self):
        """分析DELETE语句"""
        print("分析DELETE语句...")
        
        # 检查DELETE关键字
        if not self._expect_keyword("DELETE"):
            return
        
        # 检查FROM关键字
        if not self._expect_keyword("FROM"):
            return
        
        # 分析表名
        table_name = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            table_name = self._current_token().value
            self._advance()
        else:
            self.semantic_error("期望表名")
            return
        
        # 检查表是否存在
        if table_name and not self.check_table_exists(table_name):
            current_token = self._current_token()
            if current_token:
                self.semantic_error(f"表 '{table_name}' 不存在", current_token.line, current_token.column)
        
        # 分析WHERE子句
        where_condition = self._analyze_where_clause()
        if not where_condition:
            self.semantic_error("DELETE语句必须包含WHERE子句以确保安全")
            return
        
        # 生成四元式
        if table_name:
            table_temp = self.generate_temp()
            self.emit("FROM", table_name, "-", table_temp)
            
            # 生成WHERE四元式
            where_temp = self.generate_temp()
            self.emit("WHERE", where_condition, table_temp, where_temp)
            
            # 生成DELETE四元式
            self.emit("DELETE", where_temp, "-", "-")
    
    def _analyze_drop_statement(self):
        """分析DROP语句（TABLE或DATABASE）"""
        print("分析DROP语句...")
        
        # 检查DROP关键字
        if not self._expect_keyword("DROP"):
            return
        
        # 检查下一个关键字是TABLE还是DATABASE
        current = self._current_token()
        if not current or current.type != TokenType.KEYWORD:
            self.semantic_error("DROP后面必须跟TABLE或DATABASE关键字")
            return
        
        next_keyword = current.value.upper()
        if next_keyword == "TABLE":
            self._analyze_drop_table_statement()
        elif next_keyword == "DATABASE":
            self._analyze_drop_database_statement()
        elif next_keyword == "USER":
            self._analyze_drop_user_statement()
        else:
            self.semantic_error(f"DROP后面不支持的关键字: {next_keyword}")
    
    def _analyze_drop_table_statement(self):
        """分析DROP TABLE语句"""
        print("分析DROP TABLE语句...")
        
        # 检查TABLE关键字
        if not self._expect_keyword("TABLE"):
            return
        
        # 分析表名
        table_name = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            table_name = self._current_token().value
            current_token = self._current_token()
            self.add_symbol(table_name, "table", current_token.line, current_token.column)
            self._advance()
        else:
            self.semantic_error("期望表名")
            return
        
        # 语义检查：验证表是否存在
        if table_name and not self.check_table_exists(table_name):
            current_token = self._current_token()
            if current_token:
                self.semantic_error(f"表 '{table_name}' 不存在", current_token.line, current_token.column)
        
        # 生成四元式
        if table_name:
            self.emit("DROP", table_name, "-", "-")
    
    def _analyze_where_clause(self) -> Optional[str]:
        """分析WHERE子句"""
        if self._current_token() and self._current_token().value.upper() == "WHERE":
            self._advance()  # 跳过WHERE关键字
            return self._analyze_condition()
        return None
    
    def _analyze_condition(self) -> Optional[str]:
        """分析条件表达式 - 对应 Condition -> LogicalExpr"""
        return self._analyze_logical_expr()
    
    def _analyze_logical_expr(self) -> Optional[str]:
        """分析逻辑表达式 - 对应 LogicalExpr -> SimpleCondition LogicalRest"""
        print("分析逻辑表达式...")
        
        # 分析简单条件
        left_condition = self._analyze_simple_condition()
        if not left_condition:
            return None
        
        # 分析逻辑表达式剩余部分
        right_part = self._analyze_logical_rest()
        
        if right_part:
            # 有逻辑操作符和右操作数
            operator, right_condition = right_part
            
            # 生成逻辑操作四元式
            result_temp = self.generate_temp()
            self.emit(operator, left_condition, right_condition, result_temp)
            
            return f"({left_condition} {operator} {right_condition})"
        else:
            return left_condition
    
    def _analyze_logical_rest(self) -> Optional[Tuple[str, str]]:
        """分析逻辑表达式剩余部分 - 对应 LogicalRest -> LogicalOp LogicalExpr | ε"""
        print("分析逻辑表达式剩余部分...")
        
        current = self._current_token()
        if current and current.type == TokenType.KEYWORD and current.value.upper() in ['AND', 'OR']:
            # 分析逻辑操作符
            operator = current.value.upper()
            self._advance()
            
            # 递归分析右边的逻辑表达式
            right_condition = self._analyze_logical_expr()
            if right_condition:
                return (operator, right_condition)
            else:
                self.semantic_error("期望逻辑表达式")
                return None
        
        # 空产生式，返回None
        return None
    
    def _analyze_simple_condition(self) -> Optional[str]:
        """分析简单条件 - 对应 SimpleCondition -> QualifiedID CompOp CondValue | ( Condition )"""
        print("分析简单条件...")
        
        current = self._current_token()
        if not current:
            return None
        
        # 检查是否是括号表达式
        if current.value == '(':
            self._advance()  # 跳过左括号
            
            # 递归分析条件表达式
            condition = self._analyze_condition()
            if not condition:
                return None
            
            # 检查右括号
            if not self._current_token() or self._current_token().value != ')':
                self.semantic_error("期望 ')'")
                return None
            self._advance()  # 跳过右括号
            
            return f"({condition})"
        
        # 普通比较条件：QualifiedID CompOp CondValue 或 AggregateFunc CompOp CondValue
        # 检查是否是聚合函数
        if (current.type == TokenType.KEYWORD and 
            current.value.upper() in {'COUNT', 'SUM', 'AVG', 'MAX', 'MIN', 'STDDEV', 'VARIANCE'}):
            left_operand = self._analyze_aggregate_function()
        else:
            left_operand = self._analyze_qualified_identifier()
        
        if not left_operand:
            self.semantic_error("期望标识符或聚合函数")
            return None
        
        # 检查操作符（包括LIKE关键词）
        current = self._current_token()
        if not current or (current.type != TokenType.OPERATOR and 
                          not (current.type == TokenType.KEYWORD and current.value.upper() == 'LIKE')):
            self.semantic_error("期望操作符")
            return None
        
        operator = self._current_token().value
        self._advance()
        
        # 检查右操作数：常量、qualified identifier 或子查询
        right_operand = None
        current = self._current_token()
        
        if current and current.type == TokenType.CONSTANT:
            # 常量
            right_operand = current.value
            self._advance()
        elif current and current.type == TokenType.IDENTIFIER:
            # Qualified identifier
            right_operand = self._analyze_qualified_identifier()
            if not right_operand:
                self.semantic_error("期望标识符或常量")
                return None
        elif current and current.value == '(':
            # 子查询
            self._advance()  # 跳过左括号
            
            # 检查是否是SELECT子查询
            current = self._current_token()
            if current and current.type == TokenType.KEYWORD and current.value.upper() == 'SELECT':
                # 进入子查询作用域
                self.enter_scope()
                
                try:
                    # 分析子查询
                    subquery_result = self._analyze_select_statement()
                    if not subquery_result:
                        self.semantic_error("子查询分析失败")
                        return None
                    
                    # 检查右括号
                    current = self._current_token()
                    if not current or current.value != ')':
                        self.semantic_error("期望 ')'")
                        return None
                    self._advance()  # 跳过右括号
                    
                    right_operand = f"({subquery_result})"
                finally:
                    # 退出子查询作用域
                    self.exit_scope()
            else:
                self.semantic_error("期望子查询")
                return None
        else:
            self.semantic_error("期望常量、标识符或子查询")
            return None
        
        # 生成比较四元式
        result_temp = self.generate_temp()
        self.emit(operator, left_operand, right_operand, result_temp)
        
        return f"{left_operand} {operator} {right_operand}"
    
    def _analyze_column_definitions(self) -> List[Tuple[str, str]]:
        """分析列定义列表"""
        columns = []
        
        while True:
            # 分析列名
            if not self._current_token() or self._current_token().type != TokenType.IDENTIFIER:
                self.semantic_error("期望列名")
                break
            
            col_name = self._current_token().value
            self._advance()
            
            # 分析数据类型
            if not self._current_token() or self._current_token().type != TokenType.KEYWORD:
                self.semantic_error("期望数据类型")
                break
            
            col_type = self._current_token().value.upper()
            if col_type not in ['INT', 'VARCHAR']:
                self.semantic_error(f"不支持的数据类型: {col_type}")
                break
            
            self._advance()
            
            # 处理VARCHAR(size)语法
            if col_type == 'VARCHAR' and self._current_token() and self._current_token().value == '(':
                self._advance()  # 跳过 '('
                
                # 检查数字
                if not self._current_token() or self._current_token().type != TokenType.CONSTANT:
                    self.semantic_error("期望VARCHAR长度")
                    break
                
                size = self._current_token().value
                col_type = f"VARCHAR({size})"
                self._advance()  # 跳过数字
                
                # 检查 ')'
                if not self._current_token() or self._current_token().value != ')':
                    self.semantic_error("期望')'")
                    break
                
                self._advance()  # 跳过 ')'
            
            columns.append((col_name, col_type))
            
            # 检查是否有更多列
            if self._current_token() and self._current_token().value == ',':
                self._advance()  # 跳过逗号
            else:
                break
        
        return columns
    
    def _analyze_value_list(self) -> List[str]:
        """分析值列表"""
        values = []
        
        while True:
            # 分析值
            if not self._current_token() or self._current_token().type not in [TokenType.CONSTANT, TokenType.IDENTIFIER]:
                self.semantic_error("期望值")
                break
            
            value = self._current_token().value
            values.append(value)
            self._advance()
            
            # 检查是否有更多值
            if self._current_token() and self._current_token().value == ',':
                self._advance()  # 跳过逗号
            else:
                break
        
        return values
    
    def _analyze_from_clause(self) -> Optional[Dict[str, Any]]:
        """分析FROM子句"""
        print("分析FROM子句...")
        
        # 检查FROM关键字
        if not self._expect_keyword("FROM"):
            return None
        
        # 分析表别名（包含表名和可选的别名）
        table_info = self._analyze_table_alias()
        if not table_info:
            return None
        
        main_table = table_info['table_name']
        alias = table_info.get('alias')
        
        # 生成FROM四元式
        table_temp = self.generate_temp()
        self.emit("FROM", main_table, "-", table_temp)
        
        result = {
            'main_table': main_table,
            'alias': alias,
            'result_temp': table_temp,
            'joins': []
        }
        
        # 分析JOIN子句（可选）
        join_info = self._analyze_join_clause(table_temp)
        if join_info:
            result['joins'] = join_info['joins']
            result['result_temp'] = join_info['result_temp']
        
        return result
    
    def _analyze_join_clause(self, base_temp: str) -> Optional[Dict[str, Any]]:
        """分析JOIN子句"""
        joins = []
        current_temp = base_temp
        
        while self._current_token() and self._current_token().value.upper() in ['JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL']:
            print("分析JOIN子句...")
            
            # 分析JOIN类型
            join_type = self._analyze_join_type()
            
            # 检查JOIN关键字
            if not self._expect_keyword("JOIN"):
                break
            
            # 分析要连接的表（支持别名）
            join_table_info = self._analyze_table_alias()
            if not join_table_info:
                break
            
            join_table = join_table_info['table_name']
            join_alias = join_table_info.get('alias')
            
            # 检查ON关键字
            if not self._expect_keyword("ON"):
                break
            
            # 分析连接条件
            join_condition = self._analyze_condition()
            if not join_condition:
                break
            
            # 生成JOIN四元式
            join_temp = self.generate_temp()
            join_spec = f"{join_type}:{join_table}:{join_condition}"
            self.emit("JOIN", join_spec, current_temp, join_temp)
            
            joins.append({
                'type': join_type,
                'table': join_table,
                'condition': join_condition
            })
            
            current_temp = join_temp
        
        if joins:
            return {
                'joins': joins,
                'result_temp': current_temp
            }
        return None
    
    def _analyze_join_type(self) -> str:
        """分析JOIN类型"""
        current = self._current_token()
        if not current:
            return "INNER"
        
        join_type = current.value.upper()
        if join_type in ['INNER', 'LEFT', 'RIGHT']:
            self._advance()
            if join_type in ['LEFT', 'RIGHT'] and self._current_token() and self._current_token().value.upper() == 'OUTER':
                self._advance()
                return f"{join_type} OUTER"
            return join_type
        elif join_type == 'FULL':
            self._advance()
            if self._current_token() and self._current_token().value.upper() == 'OUTER':
                self._advance()
                return "FULL OUTER"
            return "FULL"
        
        return "INNER"  # 默认为INNER JOIN
    
    def _analyze_order_clause(self) -> Optional[List[Tuple[str, str]]]:
        """分析ORDER BY子句"""
        if self._current_token() and self._current_token().value.upper() == "ORDER":
            print("分析ORDER BY子句...")
            self._advance()  # 跳过ORDER
            
            if not self._expect_keyword("BY"):
                return None
            
            return self._analyze_order_list()
        return None
    
    def _analyze_order_list(self) -> List[Tuple[str, str]]:
        """分析ORDER列表"""
        order_items = []
        
        while True:
            # 分析排序表达式（可能是列名或聚合函数）
            order_expression = None
            current_token = self._current_token()
            
            if not current_token:
                self.semantic_error("期望列名或聚合函数")
                break
            
            # 检查是否是聚合函数
            if (current_token.type == TokenType.KEYWORD and 
                current_token.value.upper() in {'COUNT', 'SUM', 'AVG', 'MAX', 'MIN', 'STDDEV', 'VARIANCE'}):
                order_expression = self._analyze_aggregate_function()
            elif current_token.type == TokenType.IDENTIFIER:
                # 普通列名
                order_expression = current_token.value
                self._advance()
            else:
                self.semantic_error("期望列名或聚合函数")
                break
            
            if not order_expression:
                break
            
            # 分析排序方向（ASC/DESC，默认ASC）
            direction = "ASC"
            if self._current_token() and self._current_token().value.upper() in ['ASC', 'DESC']:
                direction = self._current_token().value.upper()
                self._advance()
            
            order_items.append((order_expression, direction))
            
            # 检查是否有更多列
            if self._current_token() and self._current_token().value == ',':
                self._advance()  # 跳过逗号
            else:
                break
        
        return order_items
    
    def _analyze_group_clause(self) -> Optional[List[str]]:
        """分析GROUP BY子句"""
        if self._current_token() and self._current_token().value.upper() == "GROUP":
            print("分析GROUP BY子句...")
            self._advance()  # 跳过GROUP
            
            if not self._expect_keyword("BY"):
                return None
            
            return self._analyze_group_list()
        return None
    
    def _analyze_group_list(self) -> List[str]:
        """分析GROUP列表"""
        group_columns = []
        
        while True:
            # 分析列名
            if not self._current_token() or self._current_token().type != TokenType.IDENTIFIER:
                self.semantic_error("期望列名")
                break
            
            column_name = self._current_token().value
            group_columns.append(column_name)
            self._advance()
            
            # 检查是否有更多列
            if self._current_token() and self._current_token().value == ',':
                self._advance()  # 跳过逗号
            else:
                break
        
        return group_columns
    
    def _analyze_having_clause(self) -> Optional[str]:
        """分析HAVING子句"""
        if self._current_token() and self._current_token().value.upper() == "HAVING":
            print("分析HAVING子句...")
            self._advance()  # 跳过HAVING
            
            return self._analyze_condition()
        return None
    
    def _analyze_limit_clause(self) -> Optional[int]:
        """分析LIMIT子句"""
        if self._current_token() and self._current_token().value.upper() == "LIMIT":
            print("分析LIMIT子句...")
            self._advance()  # 跳过LIMIT
            
            # 检查数字
            if self._current_token() and self._current_token().type == TokenType.CONSTANT:
                limit_value = self._current_token().value
                if limit_value.isdigit():
                    limit_num = int(limit_value)
                    if limit_num <= 0:
                        self.semantic_error(f"LIMIT值必须为正整数，当前值: {limit_num}")
                        return None
                    self._advance()
                    return limit_num
                else:
                    self.semantic_error(f"LIMIT值必须为数字，当前值: {limit_value}")
                    return None
            else:
                self.semantic_error("LIMIT后面必须跟一个数字")
                return None
        return None
    
    def _analyze_update_statement(self):
        """分析UPDATE语句"""
        print("分析UPDATE语句...")
        
        # 检查UPDATE关键字
        if not self._expect_keyword("UPDATE"):
            return
        
        # 分析表名
        table_name = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            table_name = self._current_token().value
            current_token = self._current_token()
            self.add_symbol(table_name, "table", current_token.line, current_token.column)
            self._advance()
        else:
            self.semantic_error("期望表名")
            return
        
        # 检查表是否存在
        if table_name and not self.check_table_exists(table_name):
            current_token = self._current_token()
            if current_token:
                self.semantic_error(f"表 '{table_name}' 不存在", current_token.line, current_token.column)
        
        # 检查SET关键字
        if not self._expect_keyword("SET"):
            return
        
        # 分析SET列表
        set_items = self._analyze_set_list()
        
        # 分析WHERE子句（可选）
        where_condition = self._analyze_where_clause()
        
        # 生成四元式
        if table_name:
            # 生成UPDATE四元式
            table_temp = self.generate_temp()
            self.emit("UPDATE", table_name, "-", table_temp)
            
            # 为每个SET项生成SET四元式
            for column, value in set_items:
                self.emit("SET", f"{column}={value}", table_temp, "-")
            
            # 生成WHERE四元式（如果有条件）
            if where_condition:
                where_temp = self.generate_temp()
                self.emit("WHERE", where_condition, table_temp, where_temp)
    
    def _analyze_set_list(self) -> List[Tuple[str, str]]:
        """分析SET列表"""
        set_items = []
        
        while True:
            # 分析列名
            if not self._current_token() or self._current_token().type != TokenType.IDENTIFIER:
                self.semantic_error("期望列名")
                break
            
            column_name = self._current_token().value
            self._advance()
            
            # 检查等号
            if not self._current_token() or self._current_token().value != '=':
                self.semantic_error("期望 '='")
                break
            self._advance()
            
            # 分析值
            if not self._current_token() or self._current_token().type not in [TokenType.CONSTANT, TokenType.IDENTIFIER]:
                self.semantic_error("期望值")
                break
            
            value = self._current_token().value
            self._advance()
            
            set_items.append((column_name, value))
            
            # 检查是否有更多SET项
            if self._current_token() and self._current_token().value == ',':
                self._advance()  # 跳过逗号
            else:
                break
        
        return set_items
    
    def _analyze_use_statement(self):
        """分析USE语句 - 对应 UseStmt -> USE ID"""
        print("分析USE语句...")
        
        # 检查USE关键字
        if not self._expect_keyword("USE"):
            return
        
        # 分析数据库名
        database_name = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            database_name = self._current_token().value
            current_token = self._current_token()
            self.add_symbol(database_name, "database", current_token.line, current_token.column)
            self._advance()
        else:
            self.semantic_error("期望数据库名")
            return
        
        # 语义检查：验证数据库是否存在
        if database_name and not self.check_database_exists(database_name):
            current_token = self._current_token()
            if current_token:
                self.semantic_error(f"数据库 '{database_name}' 不存在", current_token.line, current_token.column)
            else:
                # 获取之前的token信息
                if self.current_token_index > 0:
                    prev_token = self.tokens[self.current_token_index - 1]
                    self.semantic_error(f"数据库 '{database_name}' 不存在", prev_token.line, prev_token.column)
                else:
                    self.semantic_error(f"数据库 '{database_name}' 不存在")
        else:
            # 设置当前数据库
            self.current_database = database_name
            print(f"切换到数据库: {database_name}")
        
        # 生成USE四元式
        if database_name:
            self.emit("USE", database_name, "-", "-")
    
    def _analyze_create_database_statement(self):
        """分析CREATE DATABASE语句"""
        print("分析CREATE DATABASE语句...")
        
        # 检查DATABASE关键字
        if not self._expect_keyword("DATABASE"):
            return
        
        # 分析数据库名
        database_name = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            database_name = self._current_token().value
            current_token = self._current_token()
            self.add_symbol(database_name, "database", current_token.line, current_token.column)
            self._advance()
        else:
            self.semantic_error("期望数据库名")
            return
        
        # 语义检查：验证数据库名是否已存在
        if database_name and self.check_database_exists(database_name):
            current_token = self._current_token()
            if current_token:
                self.semantic_error(f"数据库 '{database_name}' 已存在", current_token.line, current_token.column)
            else:
                # 获取之前的token信息
                if self.current_token_index > 0:
                    prev_token = self.tokens[self.current_token_index - 1]
                    self.semantic_error(f"数据库 '{database_name}' 已存在", prev_token.line, prev_token.column)
                else:
                    self.semantic_error(f"数据库 '{database_name}' 已存在")
        else:
            # 实际创建数据库
            try:
                if self.db_manager is not None:
                    created = self.db_manager.create_database(database_name)
                    print(f"创建数据库: {database_name} => {'成功' if created else '失败'}")
                else:
                    # 测试模式：模拟创建数据库
                    print(f"[测试模式] 模拟创建数据库: {database_name}")
                    # 将新数据库添加到预定义数据库列表中
                    self.predefined_databases.add(database_name)
            except Exception as e:
                self.semantic_error(f"创建数据库失败: {e}")
        
        # 生成CREATE_DATABASE四元式
        if database_name:
            self.emit("CREATE_DATABASE", database_name, "-", "-")
    
    def _analyze_create_user_statement(self):
        """分析CREATE USER语句"""
        print("分析CREATE USER语句...")
        
        # 检查USER关键字
        if not self._expect_keyword("USER"):
            return
        
        # 分析用户名
        username = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            username = self._current_token().value
            current_token = self._current_token()
            self.add_symbol(username, "user", current_token.line, current_token.column)
            self._advance()
        else:
            self.semantic_error("期望用户名")
            return
        
        # 检查是否有密码设置
        password = None
        if (self._current_token() and 
            self._current_token().type == TokenType.KEYWORD and 
            self._current_token().value.upper() == "IDENTIFIED"):
            self._advance()  # 跳过IDENTIFIED
            
            # 检查BY关键字
            if (self._current_token() and 
                self._current_token().type == TokenType.KEYWORD and 
                self._current_token().value.upper() == "BY"):
                self._advance()  # 跳过BY
                
                # 获取密码
                if self._current_token() and self._current_token().type == TokenType.CONSTANT:
                    password = self._current_token().value
                    self._advance()
                else:
                    self.semantic_error("期望密码字符串")
                    return
            else:
                self.semantic_error("期望BY关键字")
                return
        
        # 语义检查：验证用户名是否已存在
        if username and self.check_user_exists(username):
            current_token = self._current_token()
            if current_token:
                self.semantic_error(f"用户 '{username}' 已存在", current_token.line, current_token.column)
            else:
                # 获取之前的token信息
                if self.current_token_index > 0:
                    prev_token = self.tokens[self.current_token_index - 1]
                    self.semantic_error(f"用户 '{username}' 已存在", prev_token.line, prev_token.column)
                else:
                    self.semantic_error(f"用户 '{username}' 已存在")
        else:
            # 添加到预定义用户集合中（模拟创建）
            if username:
                self.predefined_users.add(username)
                print(f"创建用户: {username}")
        
        # 生成CREATE_USER四元式
        if username:
            if password:
                self.emit("CREATE_USER", username, password, "-")
            else:
                self.emit("CREATE_USER", username, "-", "-")
    
    def _analyze_drop_database_statement(self):
        """分析DROP DATABASE语句"""
        print("分析DROP DATABASE语句...")
        
        # 检查DATABASE关键字
        if not self._expect_keyword("DATABASE"):
            return
        
        # 分析数据库名
        database_name = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            database_name = self._current_token().value
            current_token = self._current_token()
            self.add_symbol(database_name, "database", current_token.line, current_token.column)
            self._advance()
        else:
            self.semantic_error("期望数据库名")
            return
        
        # 语义检查：验证数据库是否存在
        if database_name and not self.check_database_exists(database_name):
            current_token = self._current_token()
            if current_token:
                self.semantic_error(f"数据库 '{database_name}' 不存在", current_token.line, current_token.column)
            else:
                # 获取之前的token信息
                if self.current_token_index > 0:
                    prev_token = self.tokens[self.current_token_index - 1]
                    self.semantic_error(f"数据库 '{database_name}' 不存在", prev_token.line, prev_token.column)
                else:
                    self.semantic_error(f"数据库 '{database_name}' 不存在")
        else:
            # 实际删除数据库
            try:
                if self.db_manager is not None:
                    dropped = self.db_manager.drop_database(database_name, force=True)
                    print(f"删除数据库: {database_name} => {'成功' if dropped else '失败'}")
                else:
                    # 测试模式：模拟删除数据库
                    print(f"[测试模式] 模拟删除数据库: {database_name}")
                    # 从预定义数据库列表中移除
                    self.predefined_databases.discard(database_name)
            except Exception as e:
                self.semantic_error(f"删除数据库失败: {e}")
        
        # 生成DROP_DATABASE四元式
        if database_name:
            self.emit("DROP_DATABASE", database_name, "-", "-")
    
    def _analyze_drop_user_statement(self):
        """分析DROP USER语句"""
        print("分析DROP USER语句...")
        
        # 检查USER关键字
        if not self._expect_keyword("USER"):
            return
        
        # 分析用户名
        username = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            username = self._current_token().value
            current_token = self._current_token()
            self.add_symbol(username, "user", current_token.line, current_token.column)
            self._advance()
        else:
            self.semantic_error("期望用户名")
            return
        
        # 语义检查：验证用户是否存在
        if username and not self.check_user_exists(username):
            current_token = self._current_token()
            if current_token:
                self.semantic_error(f"用户 '{username}' 不存在", current_token.line, current_token.column)
            else:
                # 获取之前的token信息
                if self.current_token_index > 0:
                    prev_token = self.tokens[self.current_token_index - 1]
                    self.semantic_error(f"用户 '{username}' 不存在", prev_token.line, prev_token.column)
                else:
                    self.semantic_error(f"用户 '{username}' 不存在")
        else:
            # 从预定义用户集合中移除（模拟删除）
            if username and username in self.predefined_users:
                self.predefined_users.remove(username)
                print(f"删除用户: {username}")
        
        # 生成DROP_USER四元式
        if username:
            self.emit("DROP_USER", username, "-", "-")
    
    def _analyze_list_statement(self):
        """分析LIST/SHOW DATABASES语句"""
        print("分析LIST/SHOW DATABASES语句...")
        
        # 检查第一个关键字（LIST或SHOW）
        current = self._current_token()
        if not current or current.type != TokenType.KEYWORD:
            self.semantic_error("期望LIST或SHOW关键字")
            return
        
        first_keyword = current.value.upper()
        if first_keyword not in ["LIST", "SHOW"]:
            self.semantic_error(f"期望LIST或SHOW关键字，但得到 '{first_keyword}'")
            return
        
        self._advance()  # 跳过第一个关键字
        
        # 检查第二个关键字（DATABASES或SCHEMAS）
        current = self._current_token()
        if not current or current.type != TokenType.KEYWORD:
            self.semantic_error("期望DATABASES或SCHEMAS关键字")
            return
        
        second_keyword = current.value.upper()
        if second_keyword not in ["DATABASES", "SCHEMAS", "USERS"]:
            self.semantic_error(f"期望DATABASES、SCHEMAS或USERS关键字，但得到 '{second_keyword}'")
            return
        
        self._advance()  # 跳过第二个关键字
        
        # 生成相应的四元式
        command = f"{first_keyword}_{second_keyword}"
        if second_keyword == "USERS":
            self.emit("LIST_USERS", command, "-", "-")
        else:
            self.emit("LIST_DATABASES", command, "-", "-")
        print(f"执行命令: {command}")
    
    def _analyze_grant_statement(self):
        """分析GRANT语句 - 对应 GrantStmt -> GRANT PrivilegeList ON [ObjectType] ID TO GranteeList [GrantOption]"""
        print("分析GRANT语句...")
        
        # 检查GRANT关键字
        if not self._expect_keyword("GRANT"):
            return
        
        # 分析权限列表
        privileges = self._analyze_privilege_list()
        if not privileges:
            self.semantic_error("期望权限列表")
            return
        
        # 检查ON关键字
        if not self._expect_keyword("ON"):
            return
        
        # 分析对象类型（可选）
        object_type = self._analyze_object_type()
        
        # 分析对象名称
        object_name = None
        if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
            object_name = self._current_token().value
            current_token = self._current_token()
            self.add_symbol(object_name, "grant_object", current_token.line, current_token.column)
            self._advance()
        else:
            self.semantic_error("期望对象名称")
            return
        
        # 检查TO关键字
        if not self._expect_keyword("TO"):
            return
        
        # 分析被授权者列表
        grantees = self._analyze_grantee_list()
        if not grantees:
            self.semantic_error("期望被授权者列表")
            return
        
        # 分析GRANT选项（可选）
        grant_option = self._analyze_grant_option()
        
        # 语义检查：验证对象是否存在（如果是表）
        if object_type == "TABLE" or (not object_type and self.check_table_exists(object_name)):
            if not self.check_table_exists(object_name):
                current_token = self._current_token()
                if current_token:
                    self.semantic_error(f"表 '{object_name}' 不存在", current_token.line, current_token.column)
        elif object_type == "DATABASE":
            if not self.check_database_exists(object_name):
                current_token = self._current_token()
                if current_token:
                    self.semantic_error(f"数据库 '{object_name}' 不存在", current_token.line, current_token.column)
        
        # 生成GRANT四元式
        if object_name and privileges and grantees:
            # 构造GRANT规格：privileges:object_type:object_name:grantees:grant_option
            grant_spec = f"{','.join(privileges)}:{object_type or 'TABLE'}:{object_name}:{','.join(grantees)}"
            if grant_option:
                grant_spec += f":{grant_option}"
            
            self.emit("GRANT", grant_spec, "-", "-")
            print(f"生成GRANT四元式: {grant_spec}")
    
    def _analyze_privilege_list(self) -> List[str]:
        """分析权限列表"""
        privileges = []
        
        current = self._current_token()
        if not current:
            return privileges
        
        # 检查是否是ALL [PRIVILEGES]
        if current.value.upper() == "ALL":
            self._advance()
            # 检查是否有PRIVILEGES关键字
            if self._current_token() and self._current_token().value.upper() == "PRIVILEGES":
                self._advance()
            privileges.append("ALL")
            return privileges
        
        # 分析具体权限列表
        while True:
            current = self._current_token()
            if not current or current.type != TokenType.KEYWORD:
                break
            
            privilege = current.value.upper()
            if privilege in ['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'ALTER']:
                privileges.append(privilege)
                self._advance()
                
                # 检查是否有更多权限
                if self._current_token() and self._current_token().value == ',':
                    self._advance()  # 跳过逗号
                else:
                    break
            else:
                break
        
        return privileges
    
    def _analyze_object_type(self) -> Optional[str]:
        """分析对象类型"""
        current = self._current_token()
        if current and current.type == TokenType.KEYWORD:
            object_type = current.value.upper()
            if object_type in ['TABLE', 'DATABASE']:
                self._advance()
                return object_type
        return None
    
    def _analyze_grantee_list(self) -> List[str]:
        """分析被授权者列表"""
        grantees = []
        
        while True:
            current = self._current_token()
            if not current:
                break
            
            # 检查特殊被授权者
            if current.type == TokenType.KEYWORD:
                keyword = current.value.upper()
                if keyword == "PUBLIC":
                    grantees.append("PUBLIC")
                    self._advance()
                elif keyword in ["ROLE", "USER"]:
                    grantee_type = keyword
                    self._advance()
                    
                    # 期望标识符
                    if self._current_token() and self._current_token().type == TokenType.IDENTIFIER:
                        grantee_name = self._current_token().value
                        grantees.append(f"{grantee_type} {grantee_name}")
                        self._advance()
                    else:
                        self.semantic_error(f"期望{grantee_type}名称")
                        break
                else:
                    break
            elif current.type == TokenType.IDENTIFIER:
                # 普通用户名
                grantees.append(current.value)
                self._advance()
            else:
                break
            
            # 检查是否有更多被授权者
            if self._current_token() and self._current_token().value == ',':
                self._advance()  # 跳过逗号
            else:
                break
        
        return grantees
    
    def _analyze_grant_option(self) -> Optional[str]:
        """分析GRANT选项"""
        current = self._current_token()
        if (current and current.type == TokenType.KEYWORD and 
            current.value.upper() == "WITH"):
            self._advance()  # 跳过WITH
            
            if (self._current_token() and 
                self._current_token().type == TokenType.KEYWORD and
                self._current_token().value.upper() == "GRANT"):
                self._advance()  # 跳过GRANT
                
                if (self._current_token() and 
                    self._current_token().type == TokenType.KEYWORD and
                    self._current_token().value.upper() == "OPTION"):
                    self._advance()  # 跳过OPTION
                    return "WITH_GRANT_OPTION"
                else:
                    self.semantic_error("期望OPTION关键字")
            else:
                self.semantic_error("期望GRANT关键字")
        
        return None
    
    
    def _has_union_after_current_position(self) -> bool:
        """检查当前位置之后是否还有UNION关键字"""
        saved_index = self.current_token_index
        
        try:
            while self.current_token_index < len(self.tokens):
                token = self._current_token()
                if not token:
                    break
                
                if token.value == ';' or token.type == TokenType.EOF:
                    # 到达语句结束
                    break
                
                if token.type == TokenType.KEYWORD and token.value.upper() == 'UNION':
                    # 找到UNION关键字
                    return True
                
                self._advance()
            
            return False
        finally:
            # 恢复位置
            self.current_token_index = saved_index
    
    def _is_aggregate_function(self, attr_name: str) -> bool:
        """判断是否是聚合函数"""
        if not attr_name or '(' not in attr_name or ')' not in attr_name:
            return False
        
        # 提取函数名部分
        func_name = attr_name.split('(')[0].upper()
        return func_name in {'COUNT', 'SUM', 'AVG', 'MAX', 'MIN', 'STDDEV', 'VARIANCE'}
    
    def _print_results(self):
        """打印分析结果"""
        print("\n=== 语义分析结果 ===")
        
        # 打印四元式
        if self.enable_optimization and self.optimization_stats and self.optimization_stats.get('total_optimizations', 0) > 0:
            print("\n优化后的四元式:")
        else:
            print("\n生成的四元式:")
        
        effective_quadruples = [quad for quad in self.quadruples if quad.op != "NOP"]
        for i, quad in enumerate(effective_quadruples):
            print(f"{i:2d}: {quad}")
        
        # 打印优化统计（如果有）
        if self.enable_optimization and self.optimization_stats:
            total_optimizations = self.optimization_stats.get('total_optimizations', 0)
            if total_optimizations > 0:
                print(f"\n查询优化统计:")
                print(f"  谓词下推: {self.optimization_stats.get('predicate_pushdown', 0)} 次")
                print(f"  投影下推: {self.optimization_stats.get('projection_pushdown', 0)} 次")
                print(f"  连接重排序: {self.optimization_stats.get('join_reordering', 0)} 次")
                print(f"  常量折叠: {self.optimization_stats.get('constant_folding', 0)} 次")
                print(f"  总优化次数: {total_optimizations} 次")
        
        # 打印符号表
        print("\n符号表:")
        if self.symbol_table:
            print(f"{'符号名':<15} {'类型':<10} {'定义位置':<15}")
            print("-" * 40)
            for name, entry in self.symbol_table.items():
                location = f"({entry.line},{entry.column})" if entry.line > 0 else "-"
                print(f"{name:<15} {entry.type:<10} {location:<15}")
        else:
            print("符号表为空")
        
        # 打印错误信息
        if self.errors:
            print("\n语义错误:")
            for error in self.errors:
                print(f"  {error}")
        else:
            print("\n✓ 语义分析成功，无错误")
    
    def _record_semantic_error(self, message: str, line: int = 0, column: int = 0):
        """记录语义错误到智能纠错器"""
        # 分析错误类型
        error_type = ErrorType.SEMANTIC
        if "不存在" in message:
            error_type = ErrorType.UNDEFINED_REFERENCE
        elif "已存在" in message or "重复定义" in message:
            error_type = ErrorType.SEMANTIC
        elif "类型" in message and "不匹配" in message:
            error_type = ErrorType.TYPE_MISMATCH
        
        # 生成智能修复建议
        suggestions = self._generate_semantic_suggestions(message)
        
        error = ErrorInfo(
            error_type=error_type,
            severity=ErrorSeverity.ERROR,
            message=message,
            line=line,
            column=column,
            suggestions=suggestions
        )
        
        self.error_corrector.add_error(error)
    
    def _generate_semantic_suggestions(self, message: str) -> List[str]:
        """为语义错误生成修复建议"""
        suggestions = []
        
        if "表" in message and "不存在" in message:
            # 提取表名
            table_match = re.search(r"表 '([^']+)' 不存在", message)
            if table_match:
                table_name = table_match.group(1)
                # 查找相似的表名
                similar_tables = self._find_similar_tables(table_name)
                if similar_tables:
                    suggestions.extend([f"使用表名: {table}" for table in similar_tables])
                else:
                    suggestions.extend([
                        "检查表名拼写是否正确",
                        "确认表是否已创建",
                        "检查当前数据库是否正确"
                    ])
        
        elif "列" in message and "不存在" in message:
            # 提取列名和表名
            column_match = re.search(r"列 '([^']+)' 不存在于表 '([^']+)' 中", message)
            if column_match:
                column_name = column_match.group(1)
                table_name = column_match.group(2)
                # 查找相似的列名
                similar_columns = self._find_similar_columns(column_name, table_name)
                if similar_columns:
                    suggestions.extend([f"使用列名: {col}" for col in similar_columns])
                else:
                    suggestions.extend([
                        "检查列名拼写是否正确",
                        f"查看表 '{table_name}' 的可用列",
                        "确认表结构是否正确"
                    ])
        
        elif "数据库" in message and "不存在" in message:
            # 提取数据库名
            db_match = re.search(r"数据库 '([^']+)' 不存在", message)
            if db_match:
                db_name = db_match.group(1)
                # 查找相似的数据库名
                similar_dbs = self._find_similar_databases(db_name)
                if similar_dbs:
                    suggestions.extend([f"使用数据库: {db}" for db in similar_dbs])
                else:
                    suggestions.extend([
                        "检查数据库名拼写是否正确",
                        "确认数据库是否已创建",
                        "使用 LIST DATABASES 查看可用数据库"
                    ])
        
        elif "用户" in message and "不存在" in message:
            # 提取用户名
            user_match = re.search(r"用户 '([^']+)' 不存在", message)
            if user_match:
                user_name = user_match.group(1)
                suggestions.extend([
                    "检查用户名拼写是否正确",
                    "确认用户是否已创建",
                    "使用 LIST USERS 查看可用用户"
                ])
        
        elif "已存在" in message:
            suggestions.extend([
                "使用不同的名称",
                "添加 IF NOT EXISTS 子句（如果支持）",
                "先删除同名对象再创建"
            ])
        
        elif "重复定义" in message:
            suggestions.extend([
                "使用不同的名称",
                "检查是否重复声明",
                "确认符号的作用域"
            ])
        
        elif "列数" in message and "值数" in message and "不匹配" in message:
            suggestions.extend([
                "检查 INSERT 语句中列名和值的数量",
                "确保每个列都有对应的值",
                "检查是否遗漏或多余了列名/值"
            ])
        
        elif "必须包含WHERE子句" in message:
            suggestions.extend([
                "添加 WHERE 子句指定删除条件",
                "使用 WHERE 1=1 删除所有记录（谨慎使用）",
                "添加具体的筛选条件"
            ])
        
        return suggestions if suggestions else ["检查语义错误并修正"]
    
    def _find_similar_tables(self, table_name: str) -> List[str]:
        """查找相似的表名（基于磁盘的真实表清单）"""
        import difflib
        try:
            table_names: List[str] = []
            for db_name in self.db_manager.list_databases():
                db = self.db_manager.get_database(db_name)
                if db:
                    table_names.extend(db.list_tables())
            table_names = list(set(table_names))
            return difflib.get_close_matches(table_name, table_names, n=3, cutoff=0.6)
        except Exception:
            return []
    
    def _find_similar_columns(self, column_name: str, table_name: str) -> List[str]:
        """查找相似的列名（从磁盘读取表结构）"""
        import difflib
        try:
            # 优先当前数据库
            if self.current_database and self.check_database_exists(self.current_database):
                db = self.db_manager.get_database(self.current_database)
                if db:
                    schema = db.get_table_schema(table_name)
                    if schema and hasattr(schema, 'columns'):
                        column_names = [col.name for col in schema.columns]
                        return difflib.get_close_matches(column_name, column_names, n=3, cutoff=0.6)
            # 其他数据库
            for db_name in self.db_manager.list_databases():
                db = self.db_manager.get_database(db_name)
                if db:
                    schema = db.get_table_schema(table_name)
                    if schema and hasattr(schema, 'columns'):
                        column_names = [col.name for col in schema.columns]
                        return difflib.get_close_matches(column_name, column_names, n=3, cutoff=0.6)
        except Exception:
            pass
        return []
    
    def _find_similar_databases(self, db_name: str) -> List[str]:
        """查找相似的数据库名（基于磁盘的真实数据库清单）"""
        import difflib
        try:
            db_names = self.db_manager.list_databases()
            return difflib.get_close_matches(db_name, db_names, n=3, cutoff=0.6)
        except Exception:
            return []
    
    def _perform_error_correction(self):
        """执行智能纠错分析（使用磁盘元数据）"""
        # 分析语义错误
        if self.errors:
            try:
                dynamic_tables: Dict[str, List[str]] = {}
                for db_name in self.db_manager.list_databases():
                    db = self.db_manager.get_database(db_name)
                    if not db:
                        continue
                    for tbl in db.list_tables():
                        schema = db.get_table_schema(tbl)
                        if schema and hasattr(schema, 'columns'):
                            dynamic_tables[tbl] = [col.name for col in schema.columns]
                dynamic_databases: Set[str] = set(self.db_manager.list_databases())
                semantic_errors = self.error_corrector.analyze_semantic_errors(
                    self.errors, dynamic_tables, dynamic_databases
                )
                for error in semantic_errors:
                    self.error_corrector.add_error(error)
            except Exception as e:
                print(f"[SemanticAnalyzer] 语义错误纠错阶段构建动态元数据失败: {e}")
        
        # 生成修复建议
        suggestions = self.error_corrector.generate_correction_suggestions("", self.error_corrector.errors)
        for suggestion in suggestions:
            self.error_corrector.add_suggestion(suggestion)
    
    def get_error_report(self) -> str:
        """获取语义分析错误报告"""
        return self.error_corrector.format_error_report()
    
    def get_correction_suggestions(self) -> str:
        """获取修复建议"""
        return self.error_corrector.format_correction_suggestions()
    
    def get_error_summary(self) -> Dict[str, int]:
        """获取错误统计摘要"""
        return self.error_corrector.get_error_summary()
    
    def has_errors(self) -> bool:
        """检查是否有错误"""
        return len(self.error_corrector.errors) > 0


def main():
    """测试主函数"""
    # 创建分析器实例
    lexical_analyzer = LexicalAnalyzer()
    syntax_analyzer = SyntaxAnalyzer()
    semantic_analyzer = SemanticAnalyzer()
    
    # 测试SQL语句集合
    test_cases = [
        "USE hr_system;",                                                      # 正确语句，USE
        "USE test_db;",                                                        # 正确语句，USE
        "USE unknown_db;",                                                     # 错误：数据库不存在
        "SELECT name FROM Students;",                                           # 正确语句
        "SELECT name, age FROM Students;",                                      # 正确语句，多列
        "SELECT * FROM Students ORDER BY age ASC;",                           # 正确语句，ORDER BY
        "SELECT name FROM Students WHERE age > 20 GROUP BY major;",           # 正确语句，GROUP BY
        "SELECT s.name, t.name FROM Students s INNER JOIN Teachers t ON s.id = t.id;", # 正确语句，INNER JOIN
        "SELECT * FROM Students s LEFT JOIN Courses c ON s.id = c.teacher_id ORDER BY s.name DESC;", # 复杂查询
        "UPDATE Students SET age = 21 WHERE id = 1;",                         # 正确语句，UPDATE
        "UPDATE Students SET name = 'Alice', age = 22;",                      # 正确语句，多列UPDATE
        "DROP TABLE Students;",                                                # 正确语句，DROP TABLE
        "DROP TABLE UnknownTable;",                                           # 错误：未知表
        "SELECT name FROM Teachers;",                                          # 正确语句，不同表
        "SELECT name FROM UnknownTable;",                                      # 错误：未知表
        "SELECT unknown_col FROM Students;",                                   # 错误：未知列
        
        # UNION测试用例
        "SELECT name FROM Students UNION SELECT name FROM Teachers;",          # 正确的UNION语句
        "SELECT id, name FROM Students UNION ALL SELECT id, name FROM Teachers;", # 正确的UNION ALL语句
        "SELECT name FROM Students WHERE age > 20 UNION SELECT name FROM Teachers WHERE age < 60;", # 带条件的UNION
        "SELECT name, age FROM Students UNION SELECT name, age FROM Teachers ORDER BY name;", # 带ORDER BY的UNION
    ]
    
    for i, test_sql in enumerate(test_cases, 1):
        print(f"\n{'='*60}")
        print(f"测试用例 {i}: {test_sql}")
        print('='*60)
        
        # 词法分析
        tokens = lexical_analyzer.analyze(test_sql)
        print("词法分析结果:")
        for token in tokens:
            if token.type != TokenType.EOF:  # 不显示EOF token
                print(f"  {token}")
        
        # 语义分析
        quadruples, symbol_table, errors = semantic_analyzer.analyze(tokens)
        
        if not errors:
            print(f"\n✓ 测试用例 {i} 语义分析成功！")
        else:
            print(f"\n✗ 测试用例 {i} 语义分析发现错误")


if __name__ == "__main__":
    main()
